from uncle.util.file import upload as basic_upload

#===============================================================================
# 0 video 1 image 2 attachment
#===============================================================================
def get_file_type(input):
    input = input.lower()
    images = ['jpg','jpeg','png','gif','bmp']
    videos = ['mp4','mov','swf','flv']
    for i in images:
        if input.endswith(i):
            return 1
    for v in videos:
        if input.endswith(v):
            return 0
    return 2

def upload(file_obj, prefix, user_id):
    type = get_file_type(file_obj.name.encode('utf-8'))
    if type == 0:
        path = upload_video(file_obj, prefix, user_id)
    else:
        path = basic_upload('upload/video/' + str(user_id),
                     file_obj ,
                     pre = prefix)
        
    return (type, path)

def upload_video( file_obj, prefix, user_id ):    
    _f_name = basic_upload('upload/video/' + str(user_id),
                     file_obj ,
                     pre = prefix,
                     type = '.mp4')

    f_name = _f_name.split('.')[0]

    import os
    os.system('/usr/local/bin/ffmpeg -i ' + prefix + _f_name
              + ' -strict experimental -vcodec libx264 -vpre ipod640 -s 480x360 ' + prefix
              + f_name + '.mp4')

    os.system('/usr/local/bin/ffmpeg -i ' + prefix + _f_name +
            ' ' + prefix + f_name + '.jpg')

    #os.system('rm ' + prefix + _f_name)
    return f_name + '.mp4'